package system.impl;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class CommandLineClientListener {


	private ServerSocket listener = null;

	protected boolean listening = false;
	
	public Integer port;
	public String host;

	public Integer timeoutInterval;
	
	public CommandLineClientListener(Integer port, String host, Integer timeoutInterval) {
		this.port = port;
		this.host = host;
		this.timeoutInterval = timeoutInterval;
		try {
			if(host.equals("*"))
				listener = new ServerSocket(port, 0);
			else	
				listener = new ServerSocket(port, 0, InetAddress.getByName(host));
			listening  = true;		
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	protected Socket getClient() {
		if(listening)
			try {
				return listener.accept();
			} catch (IOException e) {
				return null;
			}
		return null;
	}
	
	public void stop() {
		listening = false;
		try {
			listener.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
